<?php

namespace app\supplier\controller;

use think\Controller;
use function GuzzleHttp\json_decode;
use function GuzzleHttp\json_encode;
use app\erp\model\Orderdb;

class Hetong extends Controller
{
    protected $uri = 'https://api.letsign.com';
    protected $version = 'v1';
    protected $appCode = 'E7046224633359500035';
    protected $appSecret = 'eAxg2Q^yQ4W9*r7q!$^0R^^53q!9^$2xMfThP6Y1#V2v2S#8*$Ber8Zseg$3&1sn';
    protected $base_url = 'https://tailongji.dixintong.com/';
    protected $HEADER = [
        "Content-Type:application/json"
    ];
    protected $param = array();
    protected $base_param = array();
    protected $url = '';
    protected $action_uri = '';
    protected $pdf_url = '';
    public $request;
    protected $signerCode = 'ent_8257eaeef01d4748931291eb523e1111'; // 执行enterprise函数获得，手动执行，执行时需要将方法设置为public 每次执行都需要修改这个值

    //e签宝电子合同 https://open.esign.cn/sandbox
    // 接口地址：https://open.esign.cn/doc/opendoc/paas_sdk_3/gekymzq5bgy6g76b
    protected $eqb_config = [
        'projectId' => '5111917615',
        'projectSecret' => 'f65b8ab1200b65c05274bf3569a01b63',
        'local' => 'http://47.111.126.189:8080',
        'init_url' => 'https://sdkapi.esign.cn/tgmonitor/rest/app!getAPIInfo2',
        'http_type' => 'HTTPS',
        'sealId' => '14f9f399-a168-48e8-b4d7-e2581b42a060',// 印章编号
        'addSignTime' => false,// 印章签署时间
    ];
    protected $eqb_config_dev = [
        'projectId' => '7439018524',
        'projectSecret' => 'bd761a0ca4101949e97525d5073be224',
        'local' => 'http://47.111.126.189:8080',
        'init_url' => 'http://smlitsm.tsign.cn:8080/tgmonitor/rest/app!getAPIInfo2',
        'http_type' => 'HTTP',
        'sealId' => '8451ef18-f509-4996-a279-9826f23ffbfb',// 印章编号
        'addSignTime' => false,// 印章签署时间
    ];

    /**
     * Title("e签宝初始化SDK")
     * Url("https://tailongji.dixintong.com/supplier/hetong/eqbInitSdk")
     */
    public function eqbInitSdk()
    {
        $post_json = [];
        $projectConfig = [];
        $projectConfig['projectId'] = $this->eqb_config['projectId'];
        $projectConfig['projectSecret'] = $this->eqb_config['projectSecret'];
        $projectConfig['itsmApiUrl'] = $this->eqb_config['init_url'];
        $httpConfig = [];
        $httpConfig['httpType'] = $this->eqb_config['http_type'];
        $signConfig = [];
        $signConfig['algorithm'] = 'HMACSHA256';
        $post_json['projectConfig'] = $projectConfig;
        $post_json['httpConfig'] = $httpConfig;
        $post_json['signConfig'] = $signConfig;
        $url = '/paas-sdk-service/timevale/init';
        $type = 'application/json';
        $result = $this->eqbCurl(json_encode($post_json), $url, $type);
        halt($result);
    }

    /**
     * Title("e签宝盖章")
     */
    protected function eqbSeal($sign_type, $file_name, $srcPdfFile, $pos_page, $posX, $posY, $keyWord)
    {
        //halt($file_name);
        $url = '/paas-sdk-service/timevale/platform/sign';
        $type = 'multipart/form-data';
        $platformSignParam = [];
        $platformSignParam['sealId'] = $this->eqb_config['sealId'];
        $platformSignParam['signType'] = $sign_type;
        $fileBean = [];
        $fileBean['fileName'] = $file_name;
        $fileBean['srcPdfFile'] = $srcPdfFile;
        //$fileBean['dstPdfFile'] = str_replace('.pdf', '_seal.pdf', $srcPdfFile);
        $fileBean['dstPdfFile'] = $_SERVER ['DOCUMENT_ROOT'] . '/uploads/Excel/hetong/' . $file_name;
        $platformSignParam['fileBean'] = $fileBean;
        $posBeans = [];
        $posBeans['posPage'] = $pos_page;
        $posBeans['posX'] = $posX;
        $posBeans['posY'] = $posY;
        $posBeans['keyWord'] = $keyWord;
        $posBeans['addSignTime'] = $this->eqb_config['addSignTime'];
        $platformSignParam['posBeans'][] = $posBeans;
        $post_data = [];
        $post_data['platformSignParam'] = json_encode($platformSignParam, JSON_UNESCAPED_UNICODE);
        $result = $this->eqbCurl($post_data, $url, $type);
        if ($result['errCode'] == 0) {
            return $result;
        } else {
            halt($result);
        }
    }

    /**
     * Title("e签宝发起json的curl请求")
     */
    protected function eqbCurl($param, $url, $type)
    {
        $header = array('Content-type: ' . $type);
        /*print_r('请求地址' . $this->eqb_config['local'] . $url);
        print_r('请求参数:');
        print_r($param);*/
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->eqb_config['local'] . $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }


    /**
     * Title("e签宝生成合同")
     */
    public function uploadOpt($out_order_no, $type, $all_page)
    {
        $name_ext = '';
        switch ($type) {
            case 'callet' :
                $name_ext = '采购合同.pdf';
                break;
            case 'post' :
                $name_ext = '送货验收单.pdf';
                break;
            case 'ysd' :
                $name_ext = '验收单.pdf';
                break;
            case 'sale' :
                $name_ext = '销售合同.pdf';
                break;
        }
        $name_ext = $out_order_no . $name_ext;
        $pdf_url = $_SERVER ['DOCUMENT_ROOT'] . '/uploads/Excel/' . $type . '/' . $name_ext;
        $sign_type = '';
        $pos_x = 0;
        $pox_y = 0;
        $keyword = '';
        $page_arr = [];
        for ($i = 1; $i <= $all_page; $i++) {
            array_push($page_arr, $i);
        }
        switch ($type) {
            case 'post' :
            case 'ysd' :
                $keyword = '泰龙吉贸易';
                $sign_type = 'Key';
                $pos_x = 30;
                break;
            case 'callet' :
                $sign_type = 'Multi';
                $pos_x = 180;
                $pox_y = 670;
                //$page_arr = [1];
                break;
            case 'sale' :
                $sign_type = 'Edges';
                $pos_x = 600;
                $pox_y = 350;
                break;
        }

        $page_list = implode(',', $page_arr);
        $result = $this->eqbSeal($sign_type, $name_ext, $pdf_url, $page_list, $pos_x, $pox_y, $keyword);

        if ($type == 'sale') {
            $sign_type = 'Multi';
            $pdf_url = $result['dstFilePath'];
            //$name_ext = str_replace('.pdf', '_seal.pdf', $name_ext);
            $result = $this->eqbSeal($sign_type, $name_ext, $pdf_url, $page_list, $pos_x, $pox_y, $keyword);
        }
        if ($result['errCode'] == 0) {
            $orderdb = new Orderdb();
            $get_order = $orderdb->where('out_order_no', $out_order_no)->find();
            $url = 'https://tailongji.dixintong.com/uploads/Excel/hetong/' . $name_ext;
            switch ($type) {
                case 'sale':
                    $get_order->save(['xsht' => $url, 'xsht_code' => $result['signServiceId']]);
                    break;
                case 'callet':
                    $get_order->save(['cght' => $url, 'cght_code' => $result['signServiceId']]);
                    break;
                case 'post':
                    $get_order->save(['shd' => $url, 'shd_code' => $result['signServiceId']]);
                    break;
                case 'ysd':
                    $get_order->save(['ysd' => $url]);
                    break;
            }
        }
        return 'success';
    }


    public function _initialize()
    {
        header("Access-Control-Allow-Origin: *");
        header('Content-Type:application/json; charset=utf-8');

        set_time_limit(0);
        ini_set('memory_limit', '256M');
        $this->param = array(
            "appCode" => $this->appCode,
            "version" => $this->version,
            "timestamp" => $this->msectime()
        );
        $this->base_param = $this->param;
        $this->pdf_url = '';
    }

    protected function msectime()
    {
        list ($msec, $sec) = explode(' ', microtime());
        $mictime = sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $mictime;
    }

    protected function makeSign()
    {
        ksort($this->param);
        $string = $this->toUrlParams();
        $string = $string . $this->appSecret;
        $result = sha1($string);
        return $result;
    }

    protected function toUrlParams()
    {
        $buff = "";
        foreach ($this->param as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v;
            }
        }
        $buff .= $this->action_uri;
        return md5($buff);
    }

    protected function doCurl()
    {
        if ($this->HEADER [0] == 'Content-Type:application/json') {
            $param = json_encode($this->param);
        } else {
            $param = $this->param;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->HEADER);
        $output = curl_exec($ch);
        curl_close($ch);
        $temp = json_decode($output, true);
        return $temp;
    }

    protected function buildParam()
    {
        $token = $this->makeSign();
        $this->param ["token"] = $token;
        if ($this->pdf_url) {
            $f = curl_file_create($this->pdf_url);
            $this->param ['contractFile'] = $f;
        }
        // print_r($this->param);
        return $this->doCurl();
    }

    // 打包
    public function zipDown($out_order_no)
    {
        $zip_name = 'uploads/Excel/hetong/' . $out_order_no . '.zip';
        $zip = new \ZipArchive ();
        $res = $zip->open($zip_name, \ZipArchive::CREATE);
        if ($res === true) {
            $orderdb = new Orderdb ();
            $get_order = $orderdb->useGlobalScope(false)->where('out_order_no', $out_order_no)->find();
            if ($get_order) {
                $get_order = $get_order->toArray();
                if ($get_order ['cght']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['cght']));
                }
                if ($get_order ['shd']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['shd']));
                }
                if ($get_order ['ysd']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['ysd']));
                }
                if ($get_order ['xsht']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['xsht']));
                }
            }
        } else {
            print_r('创建失败');
        }
        $zip->close();
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: " . filesize($zip_name));
        header("Content-Disposition: attachment; filename=\"" . basename($zip_name) . "\"");
        readfile($zip_name);
        @unlink($zip_name);
    }

    // 上传合同
    public function uploadOptOld($out_order_no, $type, $all_page)
    {
        $name_ext = '';
        switch ($type) {
            case 'callet' :
                $name_ext = '采购合同.pdf';
                break;
            case 'post' :
                $name_ext = '送货验收单.pdf';
                break;
            case 'ysd' :
                $name_ext = '验收单.pdf';
                break;
            case 'sale' :
                $name_ext = '销售合同.pdf';
                break;
        }
        $this->pdf_url = $_SERVER ['DOCUMENT_ROOT'] . '/uploads/Excel/' . $type . '/' . $out_order_no . $name_ext;

        $this->url = $this->uri . '/open-api-lite/contract/file';
        $this->action_uri = '/open-api-lite/contract/file';
        $this->HEADER = [
            "Content-Type:multipart/form-data"
        ];
        $output = $this->buildParam();
        // print_r($output);
        $contractCode = $output ['data'] ['contractCode'];
        $orderdb = new Orderdb ();
        switch ($type) {
            case 'callet' :
                $save_data ['cght_code'] = $contractCode;
                break;
            case 'post' :
                $save_data ['shd_code'] = $contractCode;
                break;
            case 'ysd' :
                $save_data ['ysd_code'] = $contractCode;
                break;
            case 'sale' :
                $save_data ['xsht_code'] = $contractCode;
                break;
        }
        $orderdb->useGlobalScope(false)->where('out_order_no', $out_order_no)->update($save_data);
        $this->autoSign($contractCode, $out_order_no, $type, $all_page);
        //print_r ( $output );
        return 'success';
        // print_r ( $output );
    }

    public function autoSign($contractCode, $out_order_no, $type, $all_page)
    {
        $this->url = $this->uri . '/open-api-lite/contract/sign/auto';
        $this->action_uri = '/open-api-lite/contract/sign/auto';
        $this->HEADER = [
            "Content-Type:application/json"
        ];
        $this->pdf_url = '';
        $this->param = $this->base_param;
        $this->param ['signerCode'] = $this->signerCode;
        $this->param ['contractCode'] = $contractCode;
        $this->param ['autoSignAuthorization'] = '1';
        $this->param ['transactionCode'] = $type . '_' . $out_order_no . '_' . time() . rand(100, 999);
        // print_r ( $this );
        switch ($type) {
            case 'sale' :
                // 销售合同
                // $this->param['scanPage'] = '1,2,3';// 扫描位置
                // $this->param['keyWord'] = '盖章处关键字';

                // $this->param ['keyWord'] = '北京市泰龙吉贸易有限公司';
                $this->param ['signCrossPage'] = 2; // 骑缝章 2是需要
                $signCoordinate = array();
                for ($i = 0; $i < $all_page; $i++) {
                    $temp ['pdfPage'] = $i + 1; // 第1页
                    $temp ['vertical'] = 350; // 纵坐标
                    $temp ['horizontal'] = 600; // 横坐标
                    array_push($signCoordinate, $temp);
                }
                $this->param ['signCoordinate'] = json_encode($signCoordinate);
                break;

            case 'post' :
                // 送货单
                //$this->param['scanPage'] = '1,2,3';// 扫描位置
                // $this->param['keyWord'] = '盖章处关键字';
                $this->param ['signCrossPage'] = 1; // 骑缝章 2是需要
                $this->param ['keyWord'] = '泰龙吉贸易';
                break;

            case 'ysd' :
                // 送货单
                //$this->param['scanPage'] = '1,2,3';// 扫描位置
                // $this->param['keyWord'] = '盖章处关键字';
                $this->param ['signCrossPage'] = 1; // 骑缝章 2是需要
                $this->param ['keyWord'] = '泰龙吉贸易';
                break;

            case 'callet' :
                // 采购合同
                // $this->param['scanPage'] = '1,2,3';// 扫描位置
                // $this->param['keyWord'] = '盖章处关键字';
                //	$this->param ['keyWord'] = '北京市泰龙吉贸易有限公司';
                $this->param ['signCrossPage'] = 1; // 骑缝章 2是需要
                $signCoordinate = array();
                for ($i = 0; $i < $all_page; $i++) {
                    $temp ['pdfPage'] = $i + 1; // 第1页
                    $temp ['vertical'] = 670; // 纵坐标
                    $temp ['horizontal'] = 180; // 横坐标
                    array_push($signCoordinate, $temp);
                }
                $this->param ['signCoordinate'] = json_encode($signCoordinate);
                break;
        }
        if ($type == 'ysd') {
            $this->param ['postSignCallback'] = 'https://tailongji.dixintong.com' . url('supplier/hetong/notiryUrl');
        } else {
            $this->param ['postSignCallback'] = 'https://tailongji.dixintong.com' . url('hetong/notiryUrl');
        }
        $this->param ['postSignCallback'] = 'https://tailongji.dixintong.com' . url('supplier/hetong/notiryUrl');
        //print_r ( $this->param );
        $result = $this->buildParam();
        /*print_r('自动签名:');
        print_r ( $result );*/
    }

    // 下载合同
    public function download($contractCode)
    {
        $this->url = $this->uri . '/open-api-lite/contract/file/download';
        $this->action_uri = '/open-api-lite/contract/file/download';
        $this->param ['contractCode'] = $contractCode;
        $result = $this->buildParam();
        return $result ['data'] ['downloadUrl'];
    }

    // 生成企业签署人
    public function enterprise()
    {
        $this->url = $this->uri . '/open-api-lite/signer/enterprise';
        $this->action_uri = '/open-api-lite/signer/enterprise';
        $this->HEADER = [
            "Content-Type:multipart/form-data"
        ];
        $this->param ['entQualificationType'] = '1';
        $this->param ['entName'] = '北京市泰龙吉贸易有限公司';
        $this->param ['entQualificationNum'] = '91110105675715354X';
        $this->param ['corporateName'] = '侯庆红';
        $this->param ['personIdType'] = '0';
        $this->param ['personName'] = '罗继东';
        $this->param ['personIdCard'] = '152502197611100710';
        $this->param ['roleType'] = '2';
        $output = $this->buildParam();
        print_r($output);
    }

    public function ajaxReturn($data, $json_option = 0)
    {
        header('Content-Type:application/json; charset=utf-8');
        exit (json_encode($data, $json_option));
    }

    public function index()
    {
        echo 'hi';
    }

    public function notiryUrl()
    {
        define('SITE_ID', 117);
        define('PARTNER_ID', 25);
        define('MEMBER_ID', 1);
        $request = request();
        $this->request = $request->param();
        if (isset ($this->request ['resultCode']) && $this->request ['resultCode'] == 1) {
            $temp = explode('_', $this->request ['transactionCode']);
            $out_order_no = $temp [1];
            $file_pre = '送货单';
            switch ($temp [0]) {
                case 'callet' :
                    $file_pre = '采购合同';
                    break;
                case 'post' :
                    $file_pre = '送货验收单';
                    break;
                case 'ysd' :
                    $file_pre = '验收单';
                    break;
                case 'sale' :
                    $file_pre = '销售合同';
                    break;
            }
            $orderdb = new Orderdb ();
            $file_path = $this->downPdf($this->request ['downloadUrl'], $file_pre, $out_order_no);
            switch ($temp [0]) {
                case 'callet' :
                    $save_data ['cght'] = $file_path;
                    break;
                case 'post' :
                    $save_data ['shd'] = $file_path;
                    break;
                case 'ysd' :
                    $save_data ['ysd'] = $file_path;
                    break;
                case 'sale' :
                    $save_data ['xsht'] = $file_path;
                    break;
            }
            $orderdb->useGlobalScope(false)->where('out_order_no', $out_order_no)->update($save_data);
            $return ['code'] = 0;
            $return ['description'] = "success";
            $this->ajaxReturn($return);
        }
        // file_put_contents('hetong_'.date('H:i:s').'.txt', $this->request);
    }

    public function downPdf($file, $file_pre, $out_order_no)
    {
        $file = file_get_contents($file);
        $time = time();
        $pic_local_path = $_SERVER ['DOCUMENT_ROOT'] . '/uploads/Excel/hetong/';
        $pic_local = $pic_local_path . $out_order_no . $file_pre . '.pdf';
        if (!file_exists($pic_local_path)) {
            @mkdir($pic_local_path, 0777);
            @chmod($pic_local_path, 0777);
        }
        file_put_contents($pic_local, $file);
        return $this->base_url . 'uploads/Excel/hetong/' . $out_order_no . $file_pre . '.pdf';
    }
}